<template>
  <div class="todo-container h-full flex">
    <!-- 左侧分类区域 25% -->
    <div class="todo-sidebar">
      <div class="p-xl">
        <AppLogo module-name="懒熊待办"/>
        <h2 class="title mb-lg">分类</h2>
        <el-tree
            v-loading="loading"
            :data="categories"
            :props="{ children: 'children', label: 'name' }"
            node-key="id"
            :default-expanded-keys="expandedKeys"
            :current-node-key="selectedCategoryId"
            :expand-on-click-node="false"
            highlight-current
            @node-click="handleNodeClick"
        />
      </div>
    </div>

    <!-- 右侧内容区域 75% -->
    <div class="todo-content">
      <router-view/>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, provide, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {getCategoryList} from '../api'
import type {Category} from '../types'
import AppLogo from '@/components/AppLogo.vue'

const router = useRouter()
const route = useRoute()

const categories = ref<Category[]>([])
const loading = ref(false)
const expandedKeys = ref<string[]>([])
const selectedCategoryId = ref<string | undefined>(undefined)

// 提供给子组件（Main.vue）
provide('selectedCategoryId', selectedCategoryId)

const fetchCategories = async () => {
  loading.value = true
  try {
    categories.value = await getCategoryList()
    // 默认展开第一个分类
    if (categories.value.length > 0 && categories.value[0]) {
      expandedKeys.value = [categories.value[0].id]
    }
    // 从路由参数中读取 categoryId
    const categoryIdFromRoute = route.query.categoryId as string | undefined
    if (categoryIdFromRoute) {
      selectedCategoryId.value = categoryIdFromRoute
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleNodeClick = (data: Category) => {
  // 如果节点未展开，则添加到展开列表
  if (!expandedKeys.value.includes(data.id)) {
    expandedKeys.value = [...expandedKeys.value, data.id]
  }
  // 更新选中的分类ID（Main.vue会监听这个变化并自动重置筛选器）
  selectedCategoryId.value = data.id
  // 更新路由参数
  router.push({
    path: '/todo',
    query: {categoryId: data.id}
  })
}

// 监听路由变化，同步 selectedCategoryId
watch(
    () => route.query.categoryId,
    (newCategoryId) => {
      selectedCategoryId.value = newCategoryId as string | undefined
    }
)

onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.todo-container {
  overflow: hidden;
}

.todo-sidebar {
  width: 25%;
  background-color: #f8f8f8;
  overflow-y: auto;
}

.todo-content {
  flex: 1;
  overflow-y: auto;
}

/* 选中节点的高亮样式 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

:deep(.el-tree-node.is-current > .el-tree-node__content:hover) {
  background-color: var(--el-color-primary-light-8);
}
</style>
